<?php
use WeChatPay\Crypto\Rsa;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Formatter;
require_once "../vendor/autoload.php";
$config = require_once "./config.php";

$headerInfo = getallheaders();
$inWechatpaySignature = $headerInfo['Wechatpay-Signature'] ?? "";// 请求头中的Wechatpay-Signature
$inWechatpayTimestamp = $headerInfo['Wechatpay-Timestamp'] ?? "";// 请求头中的Wechatpay-Timestamp
$inWechatpaySerial = $headerInfo['Wechatpay-Serial'] ?? "";// 请求头中的Wechatpay-Serial
$inWechatpayNonce = $headerInfo['Wechatpay-Nonce'] ?? "";// 请求头中的Wechatpay-Nonce
$inBody = file_get_contents('php://input');// 请根据实际情况获取，例如: file_get_contents('php://input');
$inBodyArray = (array)json_decode($inBody, true);

//\WeChatPay\AddLog(['Signature'=>$inWechatpaySignature, 'Timestamp'=>$inWechatpayTimestamp, 'Serial'=>$inWechatpaySerial, 'Nonce'=>$inWechatpayNonce, 'body'=>$inBodyArray]);

// 检查通知时间偏移量，允许5分钟之内的偏移
$timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
$verifiedStatus = (new \WeChatPay\WeChatSdk($config))->notifyVerify($inBody, $inWechatpayNonce, $inWechatpaySerial, $inWechatpayTimestamp, $inWechatpaySignature);

if ($timeOffsetStatus && $verifiedStatus['code'] == WX_RETURN_SUCCESS) {
    // 转换通知的JSON文本消息为PHP Array数组
    try {
        if (isset($inBodyArray['resource']['ciphertext'])) {
            // 使用PHP7的数据解构语法，从Array中解构并赋值变量
            $ciphertext = $inBodyArray['resource']['ciphertext'];
            $nonce = $inBodyArray['resource']['nonce'];
            $aad = $inBodyArray['resource']['associated_data'];
            // 加密文本消息解密
            $inBodyResource = AesGcm::decrypt($ciphertext, $config['apiV3Key'], $nonce, $aad);
            // 把解密后的文本转换为PHP Array数组
            $inBodyResourceArray = (array)json_decode($inBodyResource, true);
//            \WeChatPay\AddLog(['Resource'=>$inBodyResourceArray]);
        }
    } catch (\Throwable $e) {
//        \WeChatPay\AddLog(['code'=>'FAIL', 'message'=>$e->getMessage()]);
        echo json_encode(['code'=>'FAIL', 'message'=>'失败'], 256);
        die();
    }

    // TODO:在这里进行你得数据回调数据处理
//    \WeChatPay\AddLog(['code'=>'SUCCESS', 'message'=>'成功']);


    // TODO: 通知应答
    echo json_encode(['code'=>'SUCCESS', 'message'=>'成功'], 256);
    die();
} else {
    //TODO: 应答通知
//    \WeChatPay\AddLog(['code'=>'FAIL', 'message'=>'验签失败']);
    echo json_encode(['code'=>'FAIL', 'message'=>'失败'], 256);
    die();
}